package cn.yuanqiao.framework.web.service;

import cn.yuanqiao.common.constant.SysContants;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.core.domain.entity.SysRole;
import cn.yuanqiao.common.service.SysPermissionService;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.feignService.impl.ApiSystemServiceImpl;
import cn.yuanqiao.manage.domain.ManageUser;
import cn.yuanqiao.manage.service.IManageUserService;
import cn.yuanqiao.system.service.ISysRoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import cn.yuanqiao.common.core.domain.entity.SysUser;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import cn.yuanqiao.common.enums.UserStatus;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.MessageUtils;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.system.service.ISysUserService;

import java.util.*;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private IManageUserService manageUserService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String[] split = username.split("&&&");
        String tenantCode = null;
        String userName = null;
        boolean notLogin = true;
        if (split.length == 2) {
            tenantCode = split[0];
            userName = split[1];
        } else {
            notLogin = false;
            userName = split[0];
            tenantCode = SecurityUtils.getTenantCode();
        }
        SysUser user = null;
        if ("null".equals(tenantCode)) {
            ManageUser manageUser = manageUserService.selectUserByLoginName(userName);
            if (manageUser != null) {
                SysRole sysRole = sysRoleService.selectRoleByRoleKey(SysContants.MANAGEROLEFLAG);
                user = new SysUser();
                user.setDelFlag("0");
                user.setUserId(manageUser.getId());
                user.setPassword(manageUser.getPassWord());
                user.setStatus("0");
                user.setUserName(manageUser.getLoginName());
                user.setNickName(manageUser.getUserName());
                user.setAvatar(manageUser.getAvatar());
                List<SysRole> objects = new ArrayList<>();
                objects.add(sysRole);
                user.setRoles(objects);
            }
            /*Set<String> roles = new HashSet<>();
            roles.add("manageRole");
            // 权限集合
            R<String> menuPermission = apiSystemService.getMenuPermission("manageRole");
            String permissionStr = menuPermission.getData();
            Set<String> permissions = new HashSet<>();
            if(StringUtils.isNotEmpty(permissionStr)){
                String[] permissionStrArr = permissionStr.split(",");
                List<String> strs = Arrays.asList(permissionStrArr);
                permissions = new HashSet<>(strs);
            }*/

            //user.setLastPwdTime(manageUser.getLastPwdTime());
        } else {
            user = userService.selectUserByUserName(userName, tenantCode);
        }
        if (StringUtils.isNull(user)) {
            log.info("登录用户：{} 不存在.", userName);
            throw new ServiceException(MessageUtils.message("user.not.exists"));
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", userName);
            throw new ServiceException(MessageUtils.message("user.password.delete"));
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", userName);
            throw new ServiceException(MessageUtils.message("user.blocked"));
        }

        if (notLogin) {
            passwordService.validate(user);
        }

        return createLoginUser(user);
    }

    public UserDetails loadUserByUsernameAndTenant(String username, String tenantCode) throws UsernameNotFoundException {
        SysUser user = userService.selectUserByUserName(username, tenantCode);
        if (StringUtils.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException(MessageUtils.message("user.not.exists"));
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException(MessageUtils.message("user.password.delete"));
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException(MessageUtils.message("user.blocked"));
        }

        //passwordService.validate(user);

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user) {
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user), roles);
    }
}
